/**
 * HTTP 服务器
 * 提供静态文件服务和API接口
 */

const express = require('express');
const path = require('path');
const Logger = require('../utils/logger');
const config = require('../utils/config');

class HTTPServer {
  constructor(webSocketServer) {
    this.app = express();
    this.server = null;
    this.webSocketServer = webSocketServer;
    this.logger = new Logger('HTTPServer');
    this.isRunning = false;
    
    this.setupMiddleware();
    this.setupRoutes();
    this.setupErrorHandling();
  }

  /**
   * 设置中间件
   */
  setupMiddleware() {
    // 解析JSON请求体
    this.app.use(express.json({ limit: '1mb' }));
    this.app.use(express.urlencoded({ extended: true, limit: '1mb' }));
    
    // 设置CORS
    if (config.get('security.enableCors', false)) {
      const allowedOrigins = config.get('security.allowedOrigins', ['*']);
      
      this.app.use((req, res, next) => {
        const origin = req.headers.origin;
        
        if (allowedOrigins.includes('*') || allowedOrigins.includes(origin)) {
          res.header('Access-Control-Allow-Origin', origin || '*');
          res.header('Access-Control-Allow-Credentials', 'true');
          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
          res.header('Access-Control-Allow-Headers', 
            'Origin,X-Requested-With,Content-Type,Accept,Authorization,Cache-Control,Pragma'
          );
        }
        
        if (req.method === 'OPTIONS') {
          res.sendStatus(204);
        } else {
          next();
        }
      });
    }
    
    // 请求日志
    this.app.use((req, res, next) => {
      this.logger.debug(`HTTP请求`, {
        method: req.method,
        url: req.url,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      });
      next();
    });
    
    // 静态文件服务
    const staticDir = config.get('static.dir', path.join(process.cwd(), 'public'));
    this.app.use(express.static(staticDir, {
      maxAge: config.isDevelopment() ? 0 : '1d', // 开发环境不缓存
      etag: true
    }));
    
    this.logger.info(`静态文件目录配置`, { staticDir });
  }

  /**
   * 设置路由
   */
  setupRoutes() {
    // 主页路由
    this.app.get('/', (req, res) => {
      res.sendFile(path.join(config.get('static.dir'), 'index.html'));
    });

    // API路由前缀
    const apiRouter = express.Router();
    
    // 健康检查
    apiRouter.get('/health', (req, res) => {
      res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        websocket: {
          running: this.webSocketServer?.isServerRunning() || false,
          address: this.webSocketServer?.getAddress() || null
        }
      });
    });
    
    // WebSocket服务器统计
    apiRouter.get('/stats', (req, res) => {
      if (!this.webSocketServer) {
        return res.status(503).json({
          error: 'WebSocket服务器未启动'
        });
      }
      
      const stats = this.webSocketServer.getStats();
      res.json(stats);
    });
    
    // 在线用户列表
    apiRouter.get('/users/online', (req, res) => {
      if (!this.webSocketServer) {
        return res.status(503).json({
          error: 'WebSocket服务器未启动'
        });
      }
      
      const onlineUsers = this.webSocketServer.getOnlineUsers();
      res.json({
        count: onlineUsers.length,
        users: onlineUsers
      });
    });
    
    // 发送系统消息 (需要身份验证)
    apiRouter.post('/messages/system', (req, res) => {
      const { message, type = 'broadcast' } = req.body;
      
      if (!message) {
        return res.status(400).json({
          error: '消息内容不能为空'
        });
      }
      
      if (!this.webSocketServer) {
        return res.status(503).json({
          error: 'WebSocket服务器未启动'
        });
      }
      
      // 创建系统消息
      const systemMessage = {
        type: 'broadcast',
        content: {
          type: 'system_announcement',
          message,
          timestamp: new Date().toISOString()
        },
        from: 'system',
        messageId: Date.now().toString(36),
        timestamp: new Date().toISOString()
      };
      
      // 广播消息
      const sentCount = this.webSocketServer.broadcast(systemMessage);
      
      res.json({
        success: true,
        message: '系统消息已发送',
        sentTo: sentCount
      });
    });
    
    // 服务器配置信息 (仅开发环境)
    if (config.isDevelopment()) {
      apiRouter.get('/config', (req, res) => {
        const safeConfig = { ...config.getAll() };
        // 移除敏感信息
        delete safeConfig.security;
        res.json(safeConfig);
      });
    }
    
    // 使用API路由
    this.app.use('/api', apiRouter);
    
    // 404处理
    this.app.use('*', (req, res) => {
      if (req.originalUrl.startsWith('/api/')) {
        res.status(404).json({
          error: '接口不存在',
          path: req.originalUrl
        });
      } else {
        // 对于非API请求，返回主页 (SPA支持)
        res.sendFile(path.join(config.get('static.dir'), 'index.html'));
      }
    });
  }

  /**
   * 设置错误处理
   */
  setupErrorHandling() {
    // 全局错误处理
    this.app.use((error, req, res, next) => {
      this.logger.error(`HTTP服务器错误`, {
        error: error.message,
        stack: error.stack,
        url: req.url,
        method: req.method
      });
      
      if (res.headersSent) {
        return next(error);
      }
      
      const statusCode = error.statusCode || error.status || 500;
      
      res.status(statusCode).json({
        error: config.isDevelopment() ? error.message : '服务器内部错误',
        ...(config.isDevelopment() && { stack: error.stack })
      });
    });
  }

  /**
   * 启动HTTP服务器
   */
  async start() {
    if (this.isRunning) {
      this.logger.warn('HTTP服务器已在运行');
      return;
    }

    try {
      const port = config.get('server.port', 3000);
      const host = config.get('server.host', 'localhost');
      
      await new Promise((resolve, reject) => {
        this.server = this.app.listen(port, host, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
      
      this.isRunning = true;
      
      this.logger.success(`HTTP服务器启动成功`, {
        host,
        port,
        url: `http://${host}:${port}`
      });
      
    } catch (error) {
      this.logger.error('HTTP服务器启动失败', { 
        error: error.message 
      });
      throw error;
    }
  }

  /**
   * 停止HTTP服务器
   */
  async stop() {
    if (!this.isRunning || !this.server) {
      this.logger.warn('HTTP服务器未在运行');
      return;
    }

    try {
      await new Promise((resolve, reject) => {
        this.server.close((error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
      
      this.isRunning = false;
      this.server = null;
      
      this.logger.success('HTTP服务器已停止');
      
    } catch (error) {
      this.logger.error('停止HTTP服务器失败', { 
        error: error.message 
      });
      throw error;
    }
  }

  /**
   * 获取服务器信息
   */
  getServerInfo() {
    if (!this.server || !this.isRunning) {
      return null;
    }
    
    const address = this.server.address();
    return {
      host: address.address,
      port: address.port,
      family: address.family,
      isRunning: this.isRunning
    };
  }

  /**
   * 添加自定义路由
   */
  addRoute(method, path, handler) {
    this.app[method.toLowerCase()](path, handler);
    this.logger.info(`添加自定义路由`, { method, path });
  }

  /**
   * 添加中间件
   */
  addMiddleware(middleware) {
    this.app.use(middleware);
    this.logger.info('添加自定义中间件');
  }

  /**
   * 获取Express应用实例
   */
  getApp() {
    return this.app;
  }
}

module.exports = HTTPServer;